package com.reran.geek.demo.Week02.demo;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:
 * @author: WangSiTeng
 * @date: 2021/11/16
 */
public class HttpServer03 {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8079);

        ExecutorService executorService =
                Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 2);

        while (true) {
            try {
                final Socket socket = serverSocket.accept();
                executorService.execute(() -> service(socket));
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private static void service(Socket socket) {
        try {
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream, true);
            printWriter.println("HTTP/1.1 200 OK");
            printWriter.println("Content-Type:text/html;charset=utf-8");
            String responseBody = "hello socket!";
            printWriter.println("Content-Length:" + responseBody.getBytes().length);
            printWriter.println();
            printWriter.println(responseBody);
            printWriter.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
